package com.example.ai.controller;

import com.example.ai.service.AuthService;
import com.example.ai.service.EcommerceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 电商控制器，处理商品和订单相关请求
 */
@RestController
@RequestMapping("/api/ecommerce")
public class EcommerceController {
    
    private final EcommerceService ecommerceService;
    private final AuthService authService;
    
    @Autowired
    public EcommerceController(EcommerceService ecommerceService, AuthService authService) {
        this.ecommerceService = ecommerceService;
        this.authService = authService;
    }
    
    /**
     * 获取所有商品列表
     */
    @GetMapping("/products")
    public List<EcommerceService.Product> getAllProducts(@RequestHeader(value = "Authorization", required = false) String token) {
        // 验证token（可选，实际项目中可根据需求设置为必需）
        if (token != null) {
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            if (!authService.validateToken(token)) {
                // 可以选择返回空列表或抛出异常，这里简单返回所有商品
            }
        }
        return ecommerceService.getAllProducts();
    }
    
    /**
     * 根据ID获取商品详情
     */
    @GetMapping("/products/{productId}")
    public EcommerceService.Product getProductById(@PathVariable String productId) {
        return ecommerceService.getProductById(productId);
    }
    
    /**
     * 搜索商品
     */
    @GetMapping("/products/search")
    public List<EcommerceService.Product> searchProducts(@RequestParam String keyword) {
        return ecommerceService.searchProducts(keyword);
    }
    
    /**
     * 创建订单（需要登录）
     */
    @PostMapping("/orders")
    public EcommerceService.Order createOrder(
            @RequestHeader("Authorization") String token,
            @RequestBody List<String> productIds) {
        // 验证token
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        if (!authService.validateToken(token)) {
            throw new RuntimeException("未授权访问，请先登录");
        }
        
        // 获取用户ID（在实际项目中，用户ID应该从token中解析或从User对象中获取）
        String userId = authService.getUserByToken(token).getUsername();
        
        return ecommerceService.createOrder(userId, productIds);
    }
    
    /**
     * 获取订单详情
     */
    @GetMapping("/orders/{orderId}")
    public EcommerceService.Order getOrderById(
            @RequestHeader("Authorization") String token,
            @PathVariable String orderId) {
        // 验证token
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        if (!authService.validateToken(token)) {
            throw new RuntimeException("未授权访问，请先登录");
        }
        
        return ecommerceService.getOrderById(orderId);
    }
    
    /**
     * 获取当前用户的所有订单
     */
    @GetMapping("/orders")
    public List<EcommerceService.Order> getUserOrders(@RequestHeader("Authorization") String token) {
        // 验证token
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        if (!authService.validateToken(token)) {
            throw new RuntimeException("未授权访问，请先登录");
        }
        
        // 获取用户ID
        String userId = authService.getUserByToken(token).getUsername();
        
        return ecommerceService.getUserOrders(userId);
    }
}